<?php

namespace App\Admin\Controllers;

use App\Miya\Models\Info;
use App\Miya\Models\Keyword;
use App\Miya\Models\Module;
use App\Miya\Tools\TagTool;
use App\Miya\Tools\TqlTool;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Table;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;

class ModuleController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '模块管理';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Module());

        $grid->column('id', '序号');
        $grid->column('name', '模块')->label();
        $grid->column('tag', '标签')->label();
        $grid->column('one_info', '单页模式?')->editable('select', Module::$oneInfoTypes);
        $grid->column('module_extends', '模块拓展信息')->display(function () {
            return count($this->module_extends);
        })->modal('拓展信息', function ($model) {
            return new Table(['键', '值'], $model->module_extends);
        });
        $grid->column('classify_extends', '分类拓展组件')->display(function () {
            return count($this->classify_extends);
        })->modal('拓展信息', function ($model) {
            $data = array_map(function ($extend) {
                $extend['control'] = config('miya.module.controls')[$extend['control']];
                return $extend;
            }, $model->classify_extends);

            return new Table(['拓展', '组件', '默认值'], $data);
        });
        $grid->column('info_extends', '信息拓展组件')->display(function () {
            return count($this->info_extends);
        })->modal('拓展信息', function ($model) {
            $data = array_map(function ($extend) {
                $extend['control'] = config('miya.module.controls')[$extend['control']];
                return $extend;
            }, $model->info_extends);

            return new Table(['拓展', '组件', '默认值'], $data);
        });

        //禁止删除
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableView();
            if ($actions->row->id <= 4) {
                $actions->disableDelete();
            }
        });

        $grid->filter(function (Grid\Filter $filter) {
            $filter->disableIdFilter();

            $filter->like('name', '名称');
            $filter->like('tag', '标签');
        });

        //因为批量删除无法触发模型的deleted事件,所以取消批量删除
        $grid->disableBatchActions();

        return $grid;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Module());

        $form->tab('基础设置', function (Form $form) {
            $form->text('name', '模块名称')->rules(['required']);
            $form->image('avatar', '封面图片')->uniqueName()->move(getMovePath('modules'));
            $form->select('module_tql', '模块页面模版')->rules(['required'])
                ->options(TqlTool::buildTqlOptions('tql', 'modules'));
            $form->select('classify_tql', '默认分类页面模版')->rules(['required'])
                ->options(TqlTool::buildTqlOptions('tql', 'classifies'));
            $form->select('info_tql', '默认信息页面模版')->rules(['required'])
                ->options(TqlTool::buildTqlOptions('tql', 'infos'));

            $form->select('wap_module_tql', '移动端模块页面模版')->rules(['required'])
                ->options(TqlTool::buildTqlOptions('tql', 'modules', 'wap'));
            $form->select('wap_classify_tql', '移动端默认分类页面模版')->rules(['required'])
                ->options(TqlTool::buildTqlOptions('tql', 'classifies', 'wap'));
            $form->select('wap_info_tql', '移动端默认信息页面模版')->rules(['required'])
                ->options(TqlTool::buildTqlOptions('tql', 'infos', 'wap'));
        })->tab('页面设置', function (Form $form) {
            $form->text('title', '标题');
            $form->select('keyword_id', '关键词')
                ->default(app('admin_keyword')->autoSelect('modules')->id)
                ->options(Keyword::pluck('keyword', 'id'));
            $form->textarea('description', '页面描述');
            $form->UEditor('content', '页面内容');
        })->tab('高级设置', function (Form $form) {
            if ($form->isCreating()) {
                $form->text('tag', '标签')->rules([Rule::unique('modules')]);
            } elseif ($form->isEditing()) {
                $module = Module::find(request()->route('module'));
                $form->text('tag', '标签')->rules([Rule::unique('modules')->ignore($module)]);
            }
            $form->radio('one_info', '单页模式?')->default(1)->options(Module::$oneInfoTypes);
            $form->select('info_rank_type', '信息排序方式')
                ->rules(['required'])->default(1)->options(Info::$rankTypes);
            $form->number('info_paginate_num', '信息分页每页数量')->default(12)->rules(['required']);
        })->tab('拓展设置', function (Form $form) {
            $form->table('module_extends', '模块拓展信息', function (Form\NestedForm $form) {
                $form->text('key', '拓展名');
                $form->text('value', '拓展内容');
            });
            $form->table('classify_extends', '分类拓展组件', function (Form\NestedForm $form) {
                $form->text('name', '拓展名');
                $form->select('control', '控件')
                    ->default('text')
                    ->options(config('miya.module.controls'));
                $form->text('default', '默认值');
            });
            $form->table('info_extends', '信息拓展组件', function (Form\NestedForm $form) {
                $form->text('name', '拓展名');
                $form->select('control', '控件')
                    ->default('text')
                    ->options(config('miya.module.controls'));
                $form->text('default', '默认值');
            });
        });

        $form->saving(function (Form $form) {
            if ($form->name && !$form->tag) {
                $form->tag = TagTool::makeTag($form->name);
            }

            //关键词被删除情况下,重新设置关键词
            $keyword = Keyword::find($form->keyword_id);
            if (!$keyword) {
                $form->keyword_id = app('admin_keyword')->autoSelect('classifies')->id;
            }
        });

        // 自动生成后台分类路由
        if ($form->isCreating()) {
            $form->saved(function (Form $form) {
                $data = ['title' => $form->model()->name, 'icon' => 'fa-bars', 'order' => $form->model()->id + 100];
                //生成分类路由
                $classifyData = $data;
                $classifyData['parent_id'] = 16;
                $classifyData['uri'] = sprintf('module/%s/classifies', $form->model()->id);
                //生成信息路由
                $infoData = $data;
                $infoData['parent_id'] = 21;
                $infoData['uri'] = sprintf('module/%s/infos', $form->model()->id);

                DB::table('admin_menu')->insert([$classifyData, $infoData]);
            });
        }

        return $form;
    }
}
